//
//  RealEstateQaViewController.m
//  RealEstateQa
//
//  Created by 张立彬 on 13-7-9.
//  Copyright (c) 2013年 com.rong360. All rights reserved.
//

#import "RealEstateQaViewController.h"
#import "configViewController.h"
#import "DrawView.h"
#import "nextViewController.h"
#import "resultViewController.h"
#import "getdata.h"
#import "pushController.h"
#import "UITextView+Helper.h"
@interface RealEstateQaViewController ()

@end

@implementation RealEstateQaViewController

@synthesize DataBase;

@synthesize ServerData;

//当前索引
@synthesize cIndex;

//标题
@synthesize DataTitle;
//标题列表
@synthesize DataTitleList;

//描述
@synthesize DataDesc;
//描述列表
@synthesize DataDescList;

//列表数据
@synthesize DataList;
@synthesize DataListList;

//问答列表
@synthesize DataQa;
@synthesize DataQaList;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"首二套测试器";
    self.view.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_NAVIFRAME_HEIGHT);
    cIndex = 0;    
    
    //声明DrawView类
    Dv = [[DrawView alloc]init];

    wrapList = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_NAVIFRAME_HEIGHT)];
        wrapList.scrollEnabled = NO;
    //wrapList.bounces = YES;
    [self.view addSubview:wrapList];
    
    //初始化数据列表
    DataTitleList = [[NSMutableArray alloc] init];
    DataDescList = [[NSMutableArray alloc] init];
    DataListList = [[NSMutableArray alloc] init];
    DataQaList = [[NSMutableArray alloc] init];
    
    ServerData.delegate = self;
    
    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"ios"];
	NSURL *htmlUrl = [NSURL fileURLWithPath:htmlPath];
	[ServerData loadRequest:[NSURLRequest requestWithURL:htmlUrl]];
        
    //NSLog(@"加载完成");
    
    //消息监听：监听pushActive消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushCome:) name:@"pushActive" object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
    webLoading.hidden = YES;
    [webLoading stopAnimating];
    //NSLog(@"viewWillAppear");
    //NSLog(@"%i",cIndex);
    if(cIndex == 9999){
        for (UIView *view in wrapList.subviews)
        {
            [view removeFromSuperview];
        }
        
        wrapList = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, UI_NAVIFRAME_HEIGHT)];
       
        wrapList.scrollEnabled = NO;
        [self.view addSubview:wrapList];

        cIndex = 0;
        //webLoading.hidden = NO;
        //[webLoading startAnimating];
        [ServerData stringByEvaluatingJavaScriptFromString: @"location.reload();"];

        [wrapList setContentOffset:CGPointMake(320, 0) animated:YES];
        
        //NSLog(@"scount:%i",[wrapList.subviews count]);
    }
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    webLoading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    webLoading.frame = CGRectMake(150, 200, 20, 20);
    [webLoading startAnimating];
    [self.view addSubview:webLoading];

    webLoading.hidden = NO;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self loadCity];
    webLoading.hidden = YES;
    [webLoading stopAnimating];
}

//消息触发
-(void)pushCome:(NSNotification*) notification
//-(void)pushCome
{
    pushController *push = [[pushController alloc]init];
    push.notification  = notification;
    //自定义动画
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.3];
    [animation setType: kCATransitionMoveIn];
    [animation setSubtype: kCATransitionFromTop];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [self.navigationController pushViewController:push animated:NO];
    [self.navigationController.view.layer addAnimation:animation forKey:nil];

}
//点触配置去处
-(IBAction)TapPush:(id)sender{
    pushController *push = [[pushController alloc]init];
    //自定义动画
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.3];
    [animation setType: kCATransitionMoveIn];
    [animation setSubtype: kCATransitionFromTop];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [self.navigationController pushViewController:push animated:NO];
    [self.navigationController.view.layer addAnimation:animation forKey:nil];
}


//加载城市列表
-(void)loadCity
{
    [DataTitleList removeAllObjects];
    [DataDescList removeAllObjects];
    [DataListList removeAllObjects];
    [DataQaList removeAllObjects];

    NSString *code = [ServerData stringByEvaluatingJavaScriptFromString: @"window.cityData;"];
    
    //NSLog(@"数据");
    
    //NSLog(@"数据：%@", code);

    //NSLog(@"城市列表：%@",srcData[@"hpcity"]);
    [DataTitleList addObject:@"您所在的城市"];
    [DataDescList addObject:@"购房贷款受理地与房产所在地相同，原则上您在哪里买房子，就在哪里申请贷款。"];
    [DataQaList addObject:@[@"我在北京上班，在北京交的社保公积金，想在老家广州买房子，可以在北京办公积金贷款吗？",@"您要买的房屋在广州，所以只能在广州办理贷款，城市请选择广州。"]];
    //NSMutableArray *city;
    NSDictionary *srcData = [self JSONparse:code];
    //初始化城市数据
    //NSDictionary *DataCityList = srcData[@"data"];
    NSArray *DataCityList = srcData[@"data"];;//changed by lwtian 14-02-07
    [DataListList addObject:DataCityList];
    
    //NSLog(@"dataListList: %@", srcData);
    
    [self next];
}


//获取数据
-(void)getData
{    
    //取值到当前变量
    NSString *title = [DataTitleList objectAtIndex:cIndex];
    //格式化转换
    NSString *index = [NSString stringWithFormat:@"%d.",cIndex+1];
    
    DataTitle = [index stringByAppendingString:title];
        
    DataDesc = [DataDescList objectAtIndex:cIndex];
    //NSLog(@"DataDesc：%@", DataDesc);
    DataList = [DataListList objectAtIndex:cIndex];
    //NSLog(@"数据列表：%@",DataList);
    DataQa = [DataQaList objectAtIndex:cIndex];
}


//点触配置去处
-(IBAction)TapConfig:(id)sender{
    configViewController *config = [[configViewController alloc]init];
    //自定义动画
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.3];
    [animation setType: kCATransitionMoveIn];
    [animation setSubtype: kCATransitionFromTop];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [self.navigationController pushViewController:config animated:NO];
    [self.navigationController.view.layer addAnimation:animation forKey:nil];
}

//结果页
-(void)result:(NSDictionary *)resultData
{
    self.hidesBottomBarWhenPushed = YES;//add by tian
    resultViewController *result = [[resultViewController alloc]init];
    result.resultList = resultData;
    result.Mc = self;
    [[self navigationController] pushViewController:result animated:YES];
}


//上一步
-(IBAction)pre:(id)sender
{
    /*
    cIndex = cIndex - 1;
    [ServerData stringByEvaluatingJavaScriptFromString: @"fangdai.pre();"];
    if(cIndex == 1){
        BtnPre.hidden = YES;
        BtnPreImg.hidden = YES;
    }else{
        BtnPre.hidden = NO;
        BtnPreImg.hidden = NO;
    }
    [wrapList setContentOffset:CGPointMake(((cIndex-1)*320), 0) animated:YES];

    for (UIView *view in wrapList.subviews)
    {
        if (view.tag == (cIndex))
        {
            [view removeFromSuperview];
        }
    }
     */
    for (UIView *view in wrapList.subviews)
    {
        [view removeFromSuperview];
    }
    BOOL isIpone5 =   [UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(320*2, 568*2),[[UIScreen mainScreen] currentMode].size) : NO;
    if(isIpone5){
        wrapList = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 44, 320, 550)];
    }else{
        wrapList = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 44, 320, 480)];
    }
    wrapList.scrollEnabled = NO;
    [self.view addSubview:wrapList];
    
//    BtnPre.hidden = YES;
//    BtnPreImg.hidden = YES;
    cIndex = 0;
    //webLoading.hidden = NO;
    //[webLoading startAnimating];
    [ServerData stringByEvaluatingJavaScriptFromString: @"location.reload();"];
    
    [wrapList setContentOffset:CGPointMake(320, 0) animated:YES];
}

//下一步
-(void)next
{
    if(cIndex == 0){
//        BtnPre.hidden = YES;
//        BtnPreImg.hidden = YES;
    }else{
//        BtnPre.hidden = NO;
//        BtnPreImg.hidden = NO;
    }
    [self getData];
    [wrapList setContentSize:CGSizeMake(320*(1+cIndex), wrapList.frame.size.height)];
    nextViewController *next = [[nextViewController alloc]init];

    next.rc = self;
    TableList = nil;
    TableQa = nil;
    TableList = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    TableQa = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    next.TableList = TableList;
    next.TableQa = TableQa;
    next.DataTitle = DataTitle;
    next.DataDesc = DataDesc;
    next.DataList = DataList;
    next.DataQa = DataQa;
    UIView *_demo = next.view;
    _demo.frame = CGRectMake(cIndex*320, 0, 320, wrapList.frame.size.height);//初始frame
    _demo.tag = cIndex;
    [wrapList addSubview:_demo];
    //wrapList.bounces = YES;
    //NSLog(@"cindex：%i", cIndex);
    [UIView beginAnimations:nil context:nil];//动画开始
    [UIView setAnimationDuration:0.3];//设置时间
    [wrapList setContentOffset:CGPointMake((cIndex*320), 0) animated:NO];//终点frame
    [UIView commitAnimations];//动画结束
    cIndex = cIndex + 1;
}

//下面都是实现UITableViewDelegate,UITableViewDataSource两个协议中定义的方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int count = 0;
    if(tableView == TableQa){
        //NSLog(@"QaList");
         count = [DataQa count];
        if(count == 0){
            TableQa.hidden = YES;
            TableQa.frame = CGRectMake(TableQa.frame.origin.x,TableQa.frame.origin.y , TableQa.frame.size.width, 0);
        }
    }
    if(tableView == TableList){
        count = [DataList count];
        //NSLog(@"DataList");
    }
    //NSLog(@"count:%d",count);
    return count;
}

//返回一行的视图
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSUInteger row=[indexPath row];
    NSString * tableIdentifier=@"Simple table";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tableIdentifier];    
    if(cell==nil)
    {
        //当没有可复用的空闲的cell资源时(第一次载入,没翻页)
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];        
    }
    if(tableView == TableList){
        //NSLog(@"citycity:%@",DataList);
        cell.textLabel.text=[DataList objectAtIndex:row][@"desc"];//设置文字
        NSLog(@"%@",cell.textLabel.text);
        //cell.tag = [DataList objectAtIndex:row][@"value"];
        cell.accessibilityValue = [DataList objectAtIndex:row][@"value"];
        UIImage *image=[UIImage imageNamed:@"li"];//读取图片,无需扩展名
        cell.imageView.image=image;//文字左边的图片
        //调整图片大小
        [cell.imageView setTransform:CGAffineTransformMakeScale(0.5, 0.5)];
        UIImage *imageSel=[UIImage imageNamed:@"li-selected"];//读取图片,无需扩展名
        cell.imageView.highlightedImage=imageSel; //可以定义被选中后显示的图片
        cell.textLabel.highlightedTextColor = [UIColor blackColor];

        UIView *bgColorView = [[UIView alloc] init];
        bgColorView.backgroundColor = [UIColor colorWithRed:(228/255.0) green:(236/255.0) blue:(241/255.0) alpha:1];

        [cell setSelectedBackgroundView:bgColorView];
    }
    if(tableView == TableQa){
        UITextView *TextDesc = [[UITextView alloc] initWithFrame: CGRectMake(50, 0, 260, 90)];
        //设置字体
        [TextDesc setFont:[UIFont fontWithName:@"Helvetica" size:14]];
        //设置背景为透明
        [TextDesc setBackgroundColor:[UIColor clearColor]];
        //写入文本
        //[TextDesc setText:[DataQa objectAtIndex:row]];
        [TextDesc setText:[DataQa objectAtIndex:row]];
        

        //设置不可编辑
        [TextDesc setEditable:NO];
        //设置不可滚动
        [TextDesc setScrollEnabled:NO];
        
        [cell.contentView addSubview:TextDesc];
        CGRect frame;
        frame = TextDesc.frame;
        frame.size.height = [TextDesc measureHeight];//add by tian 14/3/27
        if(frame.size.height > 90){
            frame.size.height = 90;
        }
        frame.origin.y = 45 - frame.size.height/2;
        TextDesc.frame = frame;
        
        [cell.contentView addSubview:TextDesc];
        
        NSString *icon = @"wen";
        if(row %2){
            icon = @"da";
        }
        
        UIImage *image=[UIImage imageNamed:icon];//读取图片,无需扩展名
        cell.imageView.image=image;//文字左边的图片
        //调整图片大小
        [cell.imageView setTransform:CGAffineTransformMakeScale(0.5, 0.5)];
        UIImage *imageSel=[UIImage imageNamed:icon];//读取图片,无需扩展名
        cell.imageView.highlightedImage=imageSel; //可以定义被选中后显示的图片
        cell.textLabel.highlightedTextColor = [UIColor blackColor];
        
        UIView *bgColorView = [[UIView alloc] init];
        bgColorView.backgroundColor = [UIColor colorWithRed:(237/255.0) green:(242/255.0) blue:(245/255.0) alpha:1];
        bgColorView.layer.borderWidth = 0;
        [cell setBackgroundColor:[UIColor clearColor]];
        [cell setSelectedBackgroundView:bgColorView];
        //去掉背景色
        TableQa.separatorColor=UIColor.clearColor;
        //去掉边框
        TableQa.separatorStyle=UITableViewCellSeparatorStyleNone;
    }

    return cell;
}

//选中单元格之前触发
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];

    NSString *b = [@"window.fangdai.next('"stringByAppendingString:cell.accessibilityValue];
    
    NSString *c = [b stringByAppendingString:@"', '"];
    NSString *d = [c stringByAppendingString:cell.textLabel.text];
    NSString *e = [d stringByAppendingString:@"');"];
    //NSLog(@"%@",e);
    NSString *code = [ServerData stringByEvaluatingJavaScriptFromString: e];
    //NSLog(@"code:%@",code);
    
    NSDictionary *srcData = [self JSONparse:code];
    
    //NSLog(@"code:%@",srcData);
    
    //如果返回数据类型为goon
    if([srcData[@"type"] isEqual: @"goon"]){
        [DataTitleList addObject:srcData[@"title"]];
	    [DataDescList addObject:srcData[@"tips"]];
	    [DataQaList addObject:srcData[@"qaList"]];
	    [DataListList addObject:srcData[@"data"]];
	    [self next];
    }
    //如果成功
    if([srcData[@"type"] isEqual: @"success"]){
        [self result:srcData];
    }
    //如果失败
    if([srcData[@"type"] isEqual: @"fail"]){
        [self result:srcData];
    }
    return indexPath;
}

//选中单元格后触发
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

//更改高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //返回每行的高度
    //CGFloat就是float
    //return 30.0;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    //return cell.frame.size.height;
    int height;
    if(tableView == TableList){
        height = 50;
        //CGrect *frame = cell.textLabel.frame;
        //cell.textLabel.frame = CGRectMake(cell.textLabel.frame.origin.x, cell.textLabel.frame.origin.y, cell.textLabel.frame.size.width, 100);
    }

    if(tableView == TableQa){
        /*
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        //height = cell.contentView.TextDesc.frame.size.height;
        NSArray *views = [cell.contentView subviews];
        for(UIView *sub in views){
            if(views.count == 0){
                NSLog(@"xheight:%d",sub);
                height = sub.frame.size.height;
            }
        }
       // NSString *content=[DataQa objectAtIndex:indexPath.row];
        //[_sampleCell setContent:content];
        //return [_sampleCell contentHeight];
        NSLog(@"height:%d",height);
         */
        height = 80;//changed by lwtian 14-02-07
    }
    return height;
}

//在显示单元格之前触发事件
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger count = 0;
    NSInteger top = 0;
    NSInteger lineheight = 50;
    UITableView *x;
    if(tableView == TableList){
        count = DataList.count;
        x = TableList;
        top = 100;
    }
    if(tableView == TableQa){
        count = DataQa.count;
        x = TableQa;
        lineheight = 80;
        top = (DataList.count*50 + 120);
    }

    //如果是最后一行
    if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
        //end of loading
        //for example [activityIndicator stopAnimating];
        NSInteger rows = count;
        //动态改变大小
        x.frame = CGRectMake(-1,top,322, rows*lineheight);
        
        //[Dv syncHeight];
        //NSLog(@"scroll:%@", tableView.superview);
        [self syncHeight:tableView.superview];
        //DataList.frame = CGRectMake(-1,145,322, 200);
    }
    /*
    if([indexPath row] == 0){
        //默认选中第一项
        [DataList selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:0];
    }
     */
}


//画标题栏
-(void)titleBar:(UIView *)wrap title:(NSString *)title btnText:(NSString *)btnText
{
    
    UIView *foo = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    foo.backgroundColor = [UIColor colorWithRed:(26/255.0) green:(173/255.0) blue:(242/255.0) alpha:1];
    [wrap addSubview:foo];
    
    //加载标题
    //创建uilabel
    UILabel *tit = [[UILabel alloc] initWithFrame:CGRectMake(110, 6, 100, 30)];
    
    //设置背景色
    tit.backgroundColor = [UIColor clearColor];
    
    //设置tag
    //label1.tag = 91;
    
    //设置标签文本
    tit.text = title;
    //设置标签文本字体和字体大小
    tit.font = [UIFont fontWithName:@"Helvetica" size:22];
    tit.textAlignment = 1;
    //文本颜色
    tit.textColor = [UIColor whiteColor];
    
    [foo addSubview:tit];
    
    //加载完成按钮
    //UIButton *returnHome = btn;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(245, 6, 73, 33);
    [btn setTitle:btnText forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
    //[btn addTarget:self action:@selector(TapConfig:) forControlEvents:UIControlEventTouchUpInside];
    
    [foo addSubview:btn];
    
}

//同步高度
-(void)syncHeight:(UIScrollView *)scroll
{
    //滑动时显示滚动条
    scroll.showsVerticalScrollIndicator = YES;
    scroll.pagingEnabled = NO;
    if([scroll.subviews count]>0){
        CGFloat scrollViewHeight = 0.0f;
        //scroll.bounces = YES;
        for (UIView* view in scroll.subviews)
        {
            scrollViewHeight += view.frame.size.height;
        }

        UIView *theDesc = scroll.subviews[1];
        CGRect frame = theDesc.frame;
        CGFloat y = (theDesc.frame.size.height)+(theDesc.frame.origin.y);
        TableList.frame = CGRectMake(-1, y, 322, TableList.frame.size.height);
        TableQa.frame = CGRectMake(0, TableList.frame.size.height+TableList.frame.origin.y, 320, TableQa.frame.size.height);
        /*
        //取最后一个view
        UIView *_lastView = scroll.subviews[[scroll.subviews count]-1];
        
        //滚动view调试 = lastview的高度+y坐标
        scrollViewHeight = _lastView.frame.origin.y + _lastView.frame.size.height + 20;
         */
        //NSLog(@"scrollViewHeight：%f",scrollViewHeight);
        //NSLog(@"wrapListHeight：%f",wrapList.frame.size.height);
        if(scrollViewHeight > wrapList.frame.size.height){
            [scroll setContentSize:(CGSizeMake(scroll.contentSize.width, scrollViewHeight+50))];
        }else{
            if(IsIphone5){
                [scroll setContentSize:(CGSizeMake(scroll.contentSize.width, wrapList.frame.size.height+10))];
            }else{
                [scroll setContentSize:(CGSizeMake(scroll.contentSize.width, wrapList.frame.size.height-30))];
            }
        }
    }
}

//获取json
-(NSDictionary *)JSONparse:(NSString *)json
{
    NSData  *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *_result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
    return _result;
}


@end
